package com.yanyeori.framework.core.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * ApplicationContext工具类
 *
 * @author chenkuan 2020/11/27
 */
@SuppressWarnings("unchecked")
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (context == null) {
            context = applicationContext;
        }
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static String getApplicationName() {
        return context.getApplicationName();
    }

    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        return context.getBeansOfType(clazz);
    }

    public static String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotation) {
        return context.getBeanNamesForAnnotation(annotation);
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotation) {
        return context.getBeansWithAnnotation(annotation);
    }

    public static void publishEvent(ApplicationEvent event) {
        context.publishEvent(event);
    }

    public static void publishEvent(Object event) {
        context.publishEvent(event);
    }
}
